<template>
  <!-- 教师头衔设置组件 -->
  <div>
    <el-form :model="form" label-position="right" label-width="100px">
      <el-form-item label="头衔">
        <!-- 多选 -->
        <el-select
          v-model="form.label_ids"
          multiple
          collapse-tags
        >
          <el-option
            v-for="item in labels"
            :key="item.label_id"
            :label="item.label_name"
            :value="item.label_id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import service from "@/utils/service";

export default {
  data() {
    return {
      form: {
        label_ids: [],//教师所选择的头衔的id数组
      },
      labels: [],
    };
  },
  methods: {
    //获取所有的头衔
    async getAllLabels() {
      try {
        const apiUrl =
          "/teachers/label";
        const response = await service.get(apiUrl);

        if (response.data.code === 20041) {
          this.labels = response.data.data;
        }
      } catch {
        console.log("获取所有头衔出错");
      }
    },

    //保存按钮对应的方法,提交修改头衔的请求
    async handleSave() {
      try {
        const apiUrl = "/teachers/updateLabel";
        const response = await service.put(apiUrl, this.form.label_ids, {
          headers: {
            Authorization: this.$store.state.token,
          },
        });
        if (response.data.code === 20031) {
          this.$message.success("保存成功");
        } else {
          this.$message.error('修改出错，请重试');
        }
      } catch {
        console.log("修改头衔出错");
      }
    },
    //初始时获取教师所拥有的头衔
    async getCurrentLabel() {
      try {
        const apiUrl =
          "/teachers/getCurrentTeacherLabel";
        const response = await service.get(apiUrl, {
          headers: {
            Authorization: this.$store.state.token,
          },
        });

        if (response.data.code === 20041) {
          this.form.label_ids = response.data.data;
        }
      } catch {
        console.log("获取当前教师的头衔出错");
      }
    },
  },
  created() {
    this.getAllLabels();
    this.getCurrentLabel();
  },
};
</script>

<style>
</style>
